//
//  ViewController+MainSteps.m
//  JingRong_Safe_IDLFaceSDKDemoOC
//
//  Created by Zhang,Jian(MBD) on 2021/10/17.
//  Copyright © 2021 Baidu. All rights reserved.
//

#import "ViewController+MainSteps.h"
#import "BDIDInfoCollectController.h"
#import "BDIDInfoAutoCollectController.h"
#import <BDFaceBaseKit/BDFaceBaseKit.h>
#import "BDFaceAdjustParamsTool.h"
#import "FaceParameterConfig.h"
#import <BDFaceLogicLayer/BDFaceLogicLayer.h>
#import "BDFaceVerificationController.h"
#import <AipOcrSdk/AipOcrSdk.h>
#import "BDFaceAdjustParamsFileManager.h"
#import "BDFaceForUploadImageViewController.h"

/** 为什么获取token的代码不能放到客户端，原因，放到客户端是可以的，但是如果放到客户端，会有安全风险，因此，建议用户将API_KEY，SECRET_KEY 等信息放到服务端，在您的服务端做一层转发，请求到之后，将数据还抛回来即可。
 */
static NSString *BDTokenGetRequestUrl = @"http://10.138.55.237:8765/";


/// 超时时间设置
static NSUInteger BDFaceRequestTokenMaxTime = 60;

@implementation ViewController (Main_process)

- (void)getAccessToken {
    __weak typeof(self) this = self;
    NSURL *url = [NSURL URLWithString:BDTokenGetRequestUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:BDFaceRequestTokenMaxTime];
    [request setHTTPMethod:@"GET"];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
    configuration.timeoutIntervalForRequest = BDFaceRequestTokenMaxTime;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSMutableDictionary *responseDic = [NSJSONSerialization JSONObjectWithData: data
                                                                               options: NSJSONReadingMutableContainers
                                                                                 error: &error];
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *tokenString = responseDic[@"access_token"];
                this.accessToken = tokenString;
            });
            NSLog(@"%@", responseDic);
        }
    }];
    [task resume];
    
#warning developer 用户需要替换上面的变量 BDTokenGetRequestUrl，具体Url是什么，可以参考注释。 如果只是想调试，可以将token写死，如下面所示：设置self.accessToken=@"",如何获取token, 参考：https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu
    ///  如下代码，只是调试，正式代码需要从url中及时获取，需要再每次进行人脸实名认证的时候，即时获取。
    self.accessToken = @"24.4c03fb958ccd8578005e7c6c1d5f42a0.2592000.1748417951.282335-115890467";
}

/**
 初始化人脸和OCR SDK
 */
- (void)initFaceServiceAndInfoCollectService {
    __weak typeof(self) this = self;
    /// 初始化 人脸识别Service
    self.logicService = [[BDFaceLogicService alloc] initWithController:self face:^{
        [this initFaceSDK];
    } ocr:^{
        [this initOcrSDK];
    }];
}

/*
 初始化人脸SDK
 */
- (void)initFaceSDK {
    //设置默认人脸参数
    BDFaceBaseKitParamsCustomConfigItem *paramsCustomConfigItem = [[BDFaceBaseKitParamsCustomConfigItem alloc] initWithParamsConfig];
    [[BDFaceBaseKitManager sharedInstance] setParamsCustomConfigItem:paramsCustomConfigItem];
    //设置默认UI参数
    if(paramsCustomConfigItem.colorSelectMode == BDFaceBlackType) {
        BDFaceBaseKitUICustomConfigItem *uiCustomConfigItem = [[BDFaceBaseKitUICustomConfigItem alloc] initWithBlackUIConfig];
        [[BDFaceBaseKitManager sharedInstance] setUiCustomConfigItem:uiCustomConfigItem];
    } else {
        BDFaceBaseKitUICustomConfigItem *uiCustomConfigItem = [[BDFaceBaseKitUICustomConfigItem alloc] initWithUIConfig];
        [[BDFaceBaseKitManager sharedInstance] setUiCustomConfigItem:uiCustomConfigItem];
    }
    //设置默认动作活体提示参数
    BDFaceBaseKitLivenessTipCustomConfigItem *tipCustomConfigItem = [[BDFaceBaseKitLivenessTipCustomConfigItem alloc] initWithLivenessTipConfig];
    [[BDFaceBaseKitManager sharedInstance] setFaceSdkCustomLivenessTipConfig:tipCustomConfigItem];
    /// 设置licence_id 和license_name
    [[BDFaceBaseKitManager sharedInstance] initCollectWithLicenseID:FACE_LICENSE_ID andLocalLicenceName:FACE_LICENSE_NAME andExtradata:@{} callback:^(BDFaceInitRemindCode code, NSDictionary *extradata) {
        NSLog(@"%@",FACE_LICENSE_ID);
        NSLog(@"%@",FACE_LICENSE_NAME);
        NSLog(@"人脸初始化结果：%ld", (long)code);
    }];
    // 初始化设置的默认配置阈值参数
    [BDFaceAdjustParamsTool setDefaultConfig];
}

/*
 OCR SDK初始化
 */
- (void)initOcrSDK {
    NSString *licenseFile = [[NSBundle mainBundle] pathForResource:FACE_API_ORC_KEY ofType:FACE_SECRET_OCR_KEY];
    NSData *licenseFileData = [NSData dataWithContentsOfFile:licenseFile];
    [[AipOcrService shardService] authWithLicenseFileData:licenseFileData];
    NSLog(@"ocr sd version: %@", [AipOcrService ocrSdkVersion]);
}

/**
 6.4实名认证明镜SDK层调用
 */
- (void)checkFaceAction:(NSDictionary *)parameters {
    __weak typeof(self) this = self;
    [self startCheckFace:parameters response:^(int code, NSDictionary *callBack) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // 0 表示成功
            if (code == 0) {
                NSDictionary *responseDic = callBack[BDFaceLogicServiceReturnKeyForResultData];
                [this showRequestSuccessResult:responseDic];
            } else {
                NSString *errorMessage = callBack[BDFaceLogicServiceReturnKeyForResultMsg];
                [this showMainStepFailResult:errorMessage];
            }

        });
    }];
}

// 6.3实名认证SDK层调用
//- (void)checkFaceAction:(NSMutableDictionary *)parameters {
//    __weak typeof(self) this = self;
//    [self startCheckFace:parameters response:^(int code, NSDictionary *callBack) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            // 0 表示成功
//            if (code == 0) {
//                NSDictionary *responseDic = callBack[BDFaceLogicServiceReturnKeyForResultData];
//                [this showRequestSuccessResult:responseDic];
//            } else {
//                NSString *errorMessage = callBack[BDFaceLogicServiceReturnKeyForResultMsg];
//                [this showMainStepFailResult:errorMessage];
//            }
//
//        });
//    }];
//}

/**
 * 6.3结果回调成功展示逻辑
 */
//- (void)showRequestSuccessResult:(NSDictionary *)responseDic {
//        BDFaceVerificationController *verificationController = (BDFaceVerificationController *)self.navigationController.topViewController;
//        NSDictionary *errorDic = responseDic[@"error_code"];
//        int riskLevel = [responseDic[@"risk_level"] intValue];
//        if (errorDic == nil) {
//            NSString *base64Image = [responseDic objectForKey:@"dec_image"];
//            if (base64Image) {
//                NSData* data = [[NSData alloc] initWithBase64EncodedString:base64Image options:NSDataBase64DecodingIgnoreUnknownCharacters];
//                UIImage *decode_image = [UIImage imageWithData:data];
//
//            }
//            if (responseDic[@"result"][@"verify_status"]) {
//
//                if ([responseDic[@"result"][@"verify_status"] intValue] == 1) {
//                    [verificationController showBDFaceFail];
//                } else if ([responseDic[@"result"][@"verify_status"] intValue] == 2) {
//                    [verificationController showBDFaceFailGongan];
//                } else {
//                    // 如果在线活体分数大于 最低的本地传的分数，那么通过
//                    if ([responseDic[@"result"][@"score"] floatValue] > [BDConfigDataService riskScore]) {
//                        if (riskLevel == 1 || riskLevel == 2) {
//                            NSString *msg = [NSString stringWithFormat:@"risk_tag : %@",responseDic[@"risk_tag"][0]];
//                            [verificationController showBDFaceLiveFail: @""];
//                        } else {
//                            [verificationController showBDFaceSuccess];
//                        }
//                    } else {
//                        // 分数过低的时候，点击重新采集，可以执行重新采集行为
//                        [verificationController showBDFaceLiveFail:@"在线验证失败，分数过低"];
//                    }
//                }
//            }
//        } else {
//            int code = [responseDic[@"error_code"] intValue];
//            BDFaceVerificationController *vc = (BDFaceVerificationController *)self.navigationController.topViewController;
//            [vc showServerError:code riskLevel:riskLevel];
//        }
//}

// 6.3人脸核验失败结果逻辑
//- (void)showMainStepFailResult:(NSString *)errorMessage {
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//
//        // 如果topController是人脸检测loading界面，那么先退出
//        if ([self.navigationController.topViewController isKindOfClass: BDFaceVerificationController.class]) {
//            [self.navigationController popViewControllerAnimated:NO];
//        }
//        UIViewController *baseController = self.navigationController.topViewController;
//        [BDFaceToastView showToast:baseController.view text:errorMessage];
//    });
//}


/**
 6.4人脸对比调用明镜层逻辑
 */
- (void)checkFaceMatchAction:(NSDictionary *)parameters {
    __weak typeof(self) this = self;
    [self.logicService startCheckLiveCommonAction:parameters callBack:^(int resultCode, NSDictionary * _Nonnull resultDic) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // 0 表示成功
            if (resultCode == 0) {
                // 跳转自定义结果页面
                NSDictionary *responseDic = resultDic[BDFaceLogicServiceReturnKeyForResultData];
                [this showMatchSuccessResult:responseDic];
            } else {
                NSString *errorMessage = resultDic[BDFaceLogicServiceReturnKeyForResultMsg];
                [this showMainStepFailResult:errorMessage];
            }
            
        });
    }];
}

/**
  6.4人脸对比结果数据判断
 */
- (void)showMatchSuccessResult:(NSDictionary *)responseDic {
    BDFaceVerificationController *verificationController = (BDFaceVerificationController *)self.navigationController.topViewController;
    int code = [responseDic[@"error_code"] intValue];
    if (code == 0) {
        [verificationController showBDFaceSuccess];
    } else {
        int code = [responseDic[@"error_code"] intValue];
        BDFaceVerificationController *vc = (BDFaceVerificationController *)self.navigationController.topViewController;
        [vc showServerError:code];
    }
}

/**
 6.4人脸实名认证核验前处理逻辑示例代码参考
 */
- (void)startCheck {
    // 参考示例代码传入对应方案参数matchSource  0:实名认证 1:人脸对比 2:在线图片活体
    NSString *type = [[NSUserDefaults standardUserDefaults] objectForKey:@"matchSource"];
    if([type isEqual:@"0"]) {
        NSLog(@"实名认证方案");
        NSDictionary *tokenDic = @{BDFaceLogicServiceTokenKey : self.verifyToken ?: @"", @"match_source" : @(0)};
        NSMutableDictionary *tempDict = [NSMutableDictionary dictionaryWithDictionary:tokenDic];
        __weak typeof(self) this = self;
        self.logicService.showLoadingAction = ^(void) {
            [this showLoadingAction];
        };
        /// useOCR = 2 使用代码传入姓名和身份证的方式来，传入参数，直接打开采集页面，不适用OCR部分代码来采集身份证信息
        if (use_OCR == 2) {
            NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:tempDict];
    #warning developer 这里需要传入真实的姓名和身份证号，自行配置身份证类型参数verify_type，使用新方案进行二要素上报，最后才能检测成功
            // 用户姓名
            NSString *userName = @"";
            // 用户身份证号
            NSString *userIdCarNumber = @"";
            /// 姓名，证件号（身份证号）和token是必传参数
            parameters[BDFaceLogicServiceNameKey]  = userName ?: @"";
            parameters[BDFaceLogicServiceCardNumberKey]  = userIdCarNumber ?: @"";
            parameters[BDFaceLogicServiceTokenKey] = self.verifyToken;
            // 0:大陆身份证 1:港澳台居民来往内地通行证 2:外国人永久居住证 3:定居国外中国公民护照 4：港澳居民身份证
            parameters[@"verify_type"] = @"0";
            // 实名认证身份信息二要素上报接口调用
            [self reportCardInfo:parameters];
        } else {
            // 手动输入身份信息
            [BDCardInfoService showCardCollectPage:self finish:^(NSDictionary * _Nonnull personInfoDic) {
                NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:personInfoDic];
                [parameters addEntriesFromDictionary:tempDict];
               // 请求加载动画
                this.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleLarge];
                //设置指示器的位置和宽高
                this.activityIndicator.frame = CGRectMake(0, 0, 100, 100);
                this.activityIndicator.center = [UIApplication sharedApplication].keyWindow.center;
                this.activityIndicator.backgroundColor = [UIColor colorWithRed:217/255.0 green:223/255.0 blue:230/255.0 alpha:1];
                this.activityIndicator.layer.cornerRadius = 8;
                [this.activityIndicator startAnimating];
                [[UIApplication sharedApplication].keyWindow addSubview:this.activityIndicator];
                // 实名认证身份信息二要素上报接口调用
                [self reportCardInfo:parameters];
            }];
        }
    } else if ([type isEqual:@"1"]) {
        // 人脸对比
        NSLog(@"人脸对比");
        // 人脸比对传入 match_source : 1
        NSDictionary *tokenDic = @{BDFaceLogicServiceTokenKey : self.verifyToken ?: @"", @"match_source" : @(1)};
        __weak typeof(self) this = self;
        self.logicService.showLoadingAction = ^(void) {
            [this showLoadingAction];
        };

       /**
          人脸对比UI示例代码参考， demo层为方便体验集成效果提供了一套UI方便图片对比提供图片数据源 也可自行实现传入对应图片数据（base64EncodedStringWithOptions处理过的数据格式）
        */
        [BDCardInfoService showCardCollectPage:self finish:^(NSDictionary * _Nonnull personInfoDic) {
            NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:personInfoDic];
            [parameters addEntriesFromDictionary:tokenDic];
            this.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleLarge];
            //设置指示器的位置和宽高
            this.activityIndicator.frame = CGRectMake(0, 0, 100, 100);
            this.activityIndicator.center = [UIApplication sharedApplication].keyWindow.center;
            this.activityIndicator.backgroundColor = [UIColor colorWithRed:217/255.0 green:223/255.0 blue:230/255.0 alpha:1];
            this.activityIndicator.layer.cornerRadius = 8;
            [this.activityIndicator startAnimating];
            [[UIApplication sharedApplication].keyWindow addSubview:this.activityIndicator];
            // 图片对比上报请求逻辑demo示例代码
            [this reportMatchInfo:parameters];
        }];

    } else if ([type isEqual:@"2"]) {
        // 在线图片活体示例参考
        NSLog(@"在线图片活体");
        NSDictionary *tokenDic = @{BDFaceLogicServiceTokenKey : self.verifyToken ?: @"", @"match_source" : @(2)};
        __weak typeof(self) this = self;
        self.logicService.showLoadingAction = ^(void) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [this showCheckLiveLoadingAction];
            });
        };
        [self.logicService startCheckLiveCommonAction:tokenDic callBack:^(int resultCode, NSDictionary * _Nonnull resultDic) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // 0 表示成功
                        if (resultCode == 0) {
                            NSDictionary *responseDic = resultDic[@"data"];
                            [this showCheckLiveRequestSuccessResult:responseDic];
                        } else {
                            NSString *errorMessage = resultDic[BDFaceLogicServiceReturnKeyForResultMsg];
                            [self showCheckLiveFailResult:errorMessage];
                        }

                    });
        }];
    }
}

// 6.3版本调用实名认证方案
//- (void)startCheck {
//    NSDictionary *tokenDic = @{BDFaceLogicServiceTokenKey : self.accessToken ?: @""};
//    NSMutableDictionary *tempDict = [NSMutableDictionary dictionaryWithDictionary:tokenDic];
//    {
//        /// 这两个值，可以不传递
//        tempDict[BDFaceLogicServiceOnlineQualityControlKey] = [BDConfigDataService onlineImageQuality] ?: @"";
//        tempDict[BDFaceLogicServiceLivenessQualityControlKey] = [BDConfigDataService onlineLivenessQuality] ?: @"";;
//    }
//    __weak typeof(self) this = self;
//    self.logicService.showLoadingAction = ^(void) {
//        [this showLoadingAction];
//    };
//
//    /// useOCR = 2 使用代码传入姓名和身份证的方式来，传入参数，直接打开采集页面，不适用OCR部分代码来采集身份证信息
//    if ([BDConfigDataService useOCR] == 2) {
//        NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:tempDict];
//#warning developer 这里需要传入真实的姓名和身份证号，最后才能检测成功
//        // 用户姓名
//        NSString *userName = @"";
//        // 用户身份证号
//        NSString *userIdCarNumber = @"";
//        /// 姓名，证件号（身份证号）和token是必传参数
//        parameters[BDFaceLogicServiceNameKey]  = userName ?: @"";
//        parameters[BDFaceLogicServiceCardNumberKey]  = userIdCarNumber ?: @"";
//        parameters[BDFaceLogicServiceTokenKey] = @"";
//        [self checkFaceAction:parameters];
//    } else {
//        [BDCardInfoService showCardCollectPage:self finish:^(NSDictionary * _Nonnull personInfoDic) {
//            NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:personInfoDic];
//            NSString *planId = [BDConfigDataService planId];
//            parameters[BDFaceLogicServicePlanIdKey] = planId ?: @"";
//            [parameters addEntriesFromDictionary:tempDict];
//            [this checkFaceAction:parameters];
//        }];
//    }
//}

/**
    在线图片活体
 */
- (void)showCheckLiveLoadingAction {
    BDFaceVerificationController *avc = [[BDFaceVerificationController alloc] init];
    [self.navigationController pushViewController:avc animated:YES];
}

/**
 * 下面的decode_image是最终解密的照片
 */
- (void)showCheckLiveRequestSuccessResult:(NSDictionary *)responseDic {
        BDFaceVerificationController *verificationController = (BDFaceVerificationController *)self.navigationController.topViewController;
        NSDictionary *errorDic = responseDic[@"error_code"];
        int riskLevel = [responseDic[@"risk_level"] intValue];
        if (errorDic == nil) {
            NSString *base64Image = nil;
            NSArray *base64ImageArray = [responseDic objectForKey:@"dec_image"];
            if ([base64ImageArray isKindOfClass:[NSArray class]]) {
                NSArray *tempArray = (NSArray *)base64ImageArray;
                if (tempArray.count > 0) {
                    base64Image = tempArray[0];
                }
            }
            if (base64Image) {
                NSData* data = [[NSData alloc] initWithBase64EncodedString:base64Image options:NSDataBase64DecodingIgnoreUnknownCharacters];
                /// 这个是解密出来的最终的识别的图片
                UIImage *decode_image = [UIImage imageWithData:data];
            }
            if([responseDic[@"success"] boolValue]) {
                if ([responseDic[@"result"][@"liveness_score"] floatValue] > 0.8) {
                    if (riskLevel == 1 || riskLevel == 2) {
                        [verificationController showBDFaceLiveFail:@""];
                    } else {
                        [verificationController showBDFaceSuccess];
                    }
                } else {
                    // 分数过低的时候，点击重新采集，可以执行重新采集行为
                    [verificationController showBDFaceLiveFail:@"在线验证失败，分数过低"];
                }
            } else {
                [verificationController showBDFaceFail];
                NSString *msg = responseDic[@"message"];
                NSString *msgCode = responseDic[@"code"];
                NSString *msg_code = [NSString stringWithFormat:@"%@ %@", msgCode, msg];
                [BDFaceToastView showToast:[UIApplication sharedApplication].keyWindow text: msg_code];
            }
            
        }else {
            int code = [responseDic[@"error_code"] intValue];
            BDFaceVerificationController *vc = (BDFaceVerificationController *)self.navigationController.topViewController;
            [vc showServerError:code];
        }
}

- (void)showCheckLiveFailResult:(NSString *)errorMessage {
    UIViewController *baseController = self.navigationController.viewControllers[0];
    [self.navigationController popViewControllerAnimated:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [BDFaceToastView showToast:baseController.view text:errorMessage];
    });
}

/**
 
 */
/**
 * 注意！！！身份信息二要素上报接口请求示例代码！！！
 */
- (void)reportCardInfo:(NSDictionary *)cardInfoDic {
    // 身份信息上报开放api接口 ak、sk通过百度公有云平台接口获取对应token
    NSString *reportCardInfoUrl = [NSString stringWithFormat:@"https://aip.baidubce.com/rpc/2.0/brain/solution/faceprint/idcard/submit?access_token=%@",self.accessToken];
    static NSUInteger BDFaceRequestTokenMaxTime = 60;
    // 身份信息 aip地址下都需要accesstoken参数
    NSDictionary *resultDic = @{@"verify_token": self.verifyToken, @"id_name":cardInfoDic[@"name"], @"id_no":cardInfoDic[@"id_card_number"], @"certificate_type":cardInfoDic[@"verify_type"]};
    NSURL *url = [NSURL URLWithString:reportCardInfoUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:BDFaceRequestTokenMaxTime];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:resultDic options:NSJSONWritingPrettyPrinted error:nil];
    if (jsonData != nil && [jsonData isKindOfClass:[NSData class]]) {
        [request setHTTPBody:jsonData];
    }
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
    configuration.timeoutIntervalForRequest = BDFaceRequestTokenMaxTime;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    __weak typeof(self) this = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSMutableDictionary *responseDic = [NSJSONSerialization JSONObjectWithData: data
                                                                               options: NSJSONReadingMutableContainers
                                                                                 error: &error];
            NSLog(@"%@", responseDic);
            dispatch_async(dispatch_get_main_queue(), ^{
                if(responseDic[@"success"]) {
                    NSLog(@"上报身份信息核验成功");
                    [this.activityIndicator stopAnimating];
                    [this checkFaceAction:cardInfoDic];

                } else {
                    NSLog(@"上报身份信息核验失败");
                    [this.activityIndicator stopAnimating];
                }
            });
        }
    }];
    [task resume];
}

/**
 对比图片上报接口请求
 */
- (void)reportMatchInfo:(NSDictionary *)matchInfoDic {
    // 上报身份信息接口 ak、sk通过百度公有云平台接口获取对应token
    NSString *reportMatchInfoUrl = [NSString stringWithFormat:@"https://aip.baidubce.com/rpc/2.0/brain/solution/faceprint/uploadMatchImage?access_token=%@",self.accessToken];
    // 超时时间设置
    static NSUInteger BDFaceRequestTokenMaxTime = 60;
    // 身份信息 register_image 为base64
    NSDictionary *resultDic = @{@"verify_token": self.verifyToken, @"image" : matchInfoDic[@"register_image"]};
    NSURL *url = [NSURL URLWithString:reportMatchInfoUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:BDFaceRequestTokenMaxTime];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:resultDic options:NSJSONWritingPrettyPrinted error:nil];
    if (jsonData != nil && [jsonData isKindOfClass:[NSData class]]) {
        [request setHTTPBody:jsonData];
    }
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
    configuration.timeoutIntervalForRequest = BDFaceRequestTokenMaxTime;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    __weak typeof(self) this = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSMutableDictionary *responseDic = [NSJSONSerialization JSONObjectWithData: data
                                                                               options: NSJSONReadingMutableContainers
                                                                                 error: &error];
            dispatch_async(dispatch_get_main_queue(), ^{
                if(responseDic[@"success"]) {
                    NSLog(@"上报对比图片数据源成功");
                    [this.activityIndicator stopAnimating];
                    [this checkFaceMatchAction:matchInfoDic];
                } else {
                    NSLog(@"上报对比图片数据源失败");
                    [this.activityIndicator stopAnimating];
                    [BDFaceToastView showToast:[UIApplication sharedApplication].keyWindow text: @"图片数据异常"];
                }
            });
        } else {
            [this.activityIndicator stopAnimating];
            [BDFaceToastView showToast:[UIApplication sharedApplication].keyWindow text: @"人脸对比上报服务异常"];
        }
    }];
    [task resume];
}

/**
 实名认证方案
 */
- (void)startCheckFace:(NSDictionary *)dic response:(void(^)(int code, NSDictionary *callBack))response {
    NSString *name = dic[BDIDInfoCollectControllerNameKey];
    NSString *cardNumber = dic[BDIDInfoCollectControllerIdNumberKey];
    NSNumber *cardType = dic[BDIDInfoCollectControllerCarTypeKey];
    NSString *tokenString = dic[BDFaceLogicServiceTokenKey];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:dic];
    {
        // 删除从OCR传递过来的，保留其他值。
        [parameters removeObjectForKey:BDIDInfoCollectControllerNameKey];
        [parameters removeObjectForKey:BDIDInfoCollectControllerIdNumberKey];
        [parameters removeObjectForKey:BDIDInfoCollectControllerCarTypeKey];
        [parameters removeObjectForKey:BDFaceLogicServiceTokenKey];
    }
    parameters[BDFaceLogicServiceNameKey] = name ?: @"";
    parameters[BDFaceLogicServiceCardNumberKey] = cardNumber ?: @"";
    parameters[BDFaceLogicServiceTokenKey] = tokenString ?: @"";
    // 默认身份证识别
    parameters[BDFaceLogicServiceCardTypeKey] = cardType ?: @(0);
    [self.logicService startCheckLiveCommonAction:parameters callBack:^(int resultCode, NSDictionary * _Nonnull resultDic) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (response) {
                response(resultCode, resultDic);
            }
        });
    }];
}

/**
 图片对比方案
 */
- (void)startCheckFaceMatch:(NSDictionary *)dic response:(void(^)(int code, NSDictionary *callBack))response {
    NSString *tokenString = dic[BDFaceLogicServiceTokenKey];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:dic];
    {
        // 删除从OCR传递过来的，保留其他值。
        [parameters removeObjectForKey:BDIDInfoCollectControllerNameKey];
        [parameters removeObjectForKey:BDIDInfoCollectControllerIdNumberKey];
        [parameters removeObjectForKey:BDIDInfoCollectControllerCarTypeKey];
        [parameters removeObjectForKey:BDFaceLogicServiceTokenKey];
    }
    parameters[BDFaceLogicServiceTokenKey] = tokenString ?: @"";
    [self.logicService startCheckLiveCommonAction:parameters callBack:^(int resultCode, NSDictionary * _Nonnull resultDic) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (response) {
                response(resultCode, resultDic);
            }
        });
    }];
}

- (void)showLoadingAction {
    BDFaceVerificationController *avc = [[BDFaceVerificationController alloc] init];
    [self.navigationController pushViewController:avc animated:YES];
}

/**
 * 6.4实名认证下面的decode_image是最终解密的照片
 */
- (void)showRequestSuccessResult:(NSDictionary *)responseDic {
    BDFaceVerificationController *verificationController = (BDFaceVerificationController *)self.navigationController.topViewController;
    int code = [responseDic[@"error_code"] intValue];
    if (code == 0) {
        [verificationController showBDFaceSuccess];
    } else {
        int code = [responseDic[@"error_code"] intValue];
        BDFaceVerificationController *vc = (BDFaceVerificationController *)self.navigationController.topViewController;
        [vc showServerError:code];
    }
}

// 6.4 实名认核验证失败逻辑
- (void)showMainStepFailResult:(NSString *)errorMessage {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 如果topController是人脸检测loading界面，那么先退出
        if ([self.navigationController.topViewController isKindOfClass: BDFaceVerificationController.class]) {
            [self.navigationController popViewControllerAnimated:NO];
        }
        UIViewController *baseController = self.navigationController.topViewController;
        [BDFaceToastView showToast:baseController.view text:errorMessage];
    });
}


@end
